import { initCloudDB } from '@/AGC/manager'
import agconnect from '@hw-agconnect/api'
import { ElMessage } from 'element-plus'
// import { initCloudDB } from '@/AGC/manager'

/**
 * 国家码
 */
const countryCode: string = '+86'
/**
 * 语言
 */
const language: string = 'zh_CN'
/**
 * 时间间隔
 */
const interval: number = 60

/**
 * 申请手机验证码
 * @param phone 手机号
 */
export const getPhoneCode = async (phone: string, isReset: boolean = false) => {
  try {
    // 发送验证码
    await agconnect.auth().requestPhoneVerifyCode(
      countryCode,
      phone,
      isReset
        ? agconnect.auth.Action.ACTION_RESET_PASSWORD
        : agconnect.auth.Action.ACTION_REGISTER_LOGIN,
      language, //发送验证码的语言
      interval,
    )
  } catch (error) {
    ElMessage.error('申请手机验证码失败')
    Promise.reject(error)
  }
}

/**
 * 手机号注册用户
 * @param phone 手机号
 * @param password 密码
 * @param code 验证码
 * @returns Promise<SignInResult | undefined>
 */
export const createPhoneUser = async (phone: string, password: string, code: string) => {
  try {
    // 获取手机用户
    const phoneUser = new agconnect.auth.PhoneUser(countryCode, phone, password, code)
    // 获取并返回注册结果
    const signInResult = await agconnect.auth().createPhoneUser(phoneUser)
    // 初始化云数据库
    await initCloudDB()
    return signInResult
  } catch (error) {
    ElMessage.error('使用手机号注册用户失败')
    Promise.reject(error)
  }
}

/**
 * 密码登录
 * @param phone 手机号
 * @param password 密码
 * @returns Promise<SignInResult | undefined>
 */
export const credentialWithPassword = async (phone: string, password: string) => {
  try {
    // 获取登录凭证
    const credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword(
      countryCode,
      phone,
      password,
    )
    // 获取登录结果
    const signInResult = await agconnect.auth().signIn(credential)
    // 初始化云数据库
    await initCloudDB()
    return signInResult
  } catch (error) {
    ElMessage.error('使用密码登录失败')
    Promise.reject(error)
  }
}

/**
 * 验证码登录
 * @param phone 手机号
 * @param code 验证码
 * @returns Promise<SignInResult | undefined>
 */
export const credentialWithVerifyCode = async (phone: string, code: string) => {
  try {
    // 获取登录凭证
    const credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode(
      countryCode,
      phone,
      '',
      code,
    )
    // 获取登录结果
    const signInResult = await agconnect.auth().signIn(credential)
    // 初始化云数据库
    await initCloudDB()
    return signInResult
  } catch (error) {
    ElMessage.error('使用验证码登录失败')
    Promise.reject(error)
  }
}

/**
 * 重置密码
 * @param phone 手机号
 * @param newPassword 密码
 * @param code 验证码
 * @returns Promise<boolean>
 */
export const resetPasswordByPhone = async (phone: string, newPassword: string, code: string) => {
  let result: boolean = true

  try {
    await agconnect.auth().resetPasswordByPhone(countryCode, phone, newPassword, code)
  } catch (error) {
    ElMessage.error('重置密码失败')
    Promise.reject(error)
    result = false
  }

  return result
}
